<template>
	<a-modal v-bind="option" class="import-employee">
		<vxe-grid ref="grid" v-bind="gridOptions" :data="visibles.tableList" class="energy">
			<template #toolbar>
				<vxe-toolbar>
					<template #buttons>
						<a-space size="middle">
							<!-- @click="download"  -->
							<a-button type="primary" download="批量导入员工模板.xls" @click="download">
								<download-outlined />
								下载导入模板
							</a-button>
							<!-- v-action="['mk_finance_energy_drmb'] -->
							<a-upload v-model:file-list="fileList" v-bind="uploadOption" list-type="picture" :show-upload-list="{showPreviewIcon: true}">
								<a-button type="primary">
									<upload-outlined />
									导入已填模板
								</a-button>
								<template #itemRender="{file, actions}"></template>
							</a-upload>
							<!-- v-action="['mk_finance_energy_drmb']" -->
							<span class="color-faad14">
								<question-circle-outlined />
								注：选择Excel文件前，请确保导入的数据与模板的数据项一致。
							</span>
						</a-space>
					</template>
					<template #tools>
						<!-- v-action="['mk_finance_energy_czjl']" -->
						<a-button @click="openedRecords">
							<history-outlined />
							操作记录
						</a-button>
					</template>
				</vxe-toolbar>
			</template>

			<template #headerName="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #headerPhone="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #headerIdCare="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #headerSex="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #gender="{row}">{{row.gender?(row.gender === 1 ? '男' : '女' ):''}}</template>

			<template #headerEmployee="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #headerCode="{column}">
				<span v-color="{color: 'danger'}">*</span>
				{{ column.title }}
			</template>
			<template #headerErrMsg="{column}">
				{{ generateBillBtnShow ? '错误原因' : '在职证明' }}
			</template>
			<template #laborContractBeginTime="{row}">
				<span>{{ row.laborContractBeginTime }}</span>
			</template>
			<template #content="{row, rowIndex}">
				<!-- 错误原因/在职证明 -->
				<span v-if="generateBillBtnShow">{{ row.errorInfo[0] }}</span>
				<a-button style="width: 50%;" v-if="!generateBillBtnShow" type="primary" block @click="fileImageUpload(row, rowIndex)">
					<check-outlined v-if="row.uploadStatus">已上传</check-outlined>
					<plus-outlined v-else>未上传</plus-outlined>
				</a-button>
			</template>
			<template #laborContractEndTime="{row}">
				<span>{{ row.laborContractEndTime }}</span>
			</template>

			<template #pager>
				<div class="pager-box">
					<a-space class="bottom-btn" size="middle">
						<a-form ref="formRef" :model="modelRef" layout="inline">
							<a-form-item>
								<vxe-button v-if="visibles.dataList.length > 0" status="primary" @click="resetClick">重 置</vxe-button>
							</a-form-item>
							<a-form-item v-if="footerBtnShow">
								<vxe-button status="primary" :loading="loading" :disabled="generateBillBtnShow" @click="add">确认导入员工</vxe-button>
							</a-form-item>
						</a-form>
					</a-space>
					<div></div>
					<vxe-pager :layouts="['Total']" :total="visibles.total"></vxe-pager>
				</div>
			</template>
		</vxe-grid>

		<import-records-dialog v-model:visible="visibles.records" />
		<!-- 附件上传 -->
		<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" :biz-id="bizId" :multiple="false" @success="setTableattachments" />
	</a-modal>
</template>

<script lang="ts" setup>
	import {onMounted, reactive, ref, toRef, watch} from 'vue'
	import {VxeGridProps, VxePagerEvents} from 'vxe-table'
	import {message} from 'ant-design-vue'
	import {CheckOutlined, PlusOutlined, DownloadOutlined, UploadOutlined, QuestionCircleOutlined, HistoryOutlined} from '@ant-design/icons-vue'
	import {useStore} from '@/store'
	import {recordList, saveEmployee, getStorehouse, employeeTemplate, updateEmployment, enterPriseEmployeeImport} from '@/api/staff-pool'
	import {Img} from 'yuxin-base/src/types'
	// @ts-ignore
	import Snowflake from 'vue-snowflake'
	import {authHeader} from 'yuxin-base/src/utils/axios'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import ImportRecordsDialog from '@/components/contract/enterprise-customer-management/import-records-dialog.vue'

	const hasPermissions = useStore().hasPermissions

	const props = defineProps<{
		visible: boolean
	}>()

	const visibles = reactive({
		attachment: false,
		records: false,
		refId: null,
		dataList: [],
		tableList: [],
		current: 1,
		size: 15,
		total: 0
	})
	const loading = ref(false)

	const emits = defineEmits(['update:visible', 'close'])
	const option = reactive({
		title: '导入员工',
		width: 1100,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		footer: false,
		wrapClassName: 'a-modal-dialog',
		bodyStyle: {padding: '15px'},
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const grid = ref()
	const generateBillBtnShow = ref<boolean>(false)
	//底部按钮是否显示
	const footerBtnShow = ref<boolean>(false)
	//请求列表数据
	const requestInfo = ref<any[]>([])
	// 在职证明附件
	const attachments = ref<any[]>([])
	const attachmentIndex = ref<number>(-1)
	const bizId = ref<any>('')
	const fileList = ref<any[]>([])
	// 雪花ID生成器
	const node = new Snowflake.init(1, 1, 0)
	const fileImageUpload = (row, index) => {
		if (attachmentIndex.value != index) {
			bizId.value =row?.employeeId|| node.createID()
			attachments.value = []
			attachmentIndex.value = index
		}

		visibles.attachment = true
	}
	const setTableattachments = () => {
		if (!attachments.value.length) return
		visibles.tableList[attachmentIndex.value].employeeId = attachments.value[0].bizId
		let info = {id: bizId.value, uploadStatus: 1}
		updateEmployment(info).then(res => {
			visibles.tableList[attachmentIndex.value].uploadStatus = 1
			bizId.value = ''
		})
	}
	// 文件上传地址
	const uploadPicURL = import.meta.env.VITE_SERVER_URL + enterPriseEmployeeImport
	// const uploadPicURL = 'https://test.saas.server.yxpms.com/' + enterPriseEmployeeImport
	/**
	 * 文件上传地址
	 */

	const uploadOption = reactive({
		name: 'file',
		accept: '.xls',
		data: fileList,
		action: uploadPicURL,
		headers: authHeader(),
		showUploadList: false,
		onChange({file, fileList}: any) {
			const {response, status, error, percent = 0} = file
			if (status === 'done') {
				file.percent = 100
				response.data.cachedDataList.forEach(o => {
					o.uploadStatus = 0
				})
				visibles.refId = response.data.id
				// gridOptions.data = cutPage(visibles.current, visibles.size, visibles.dataList || [])
				generateBillBtnShow.value = response.data.hasErrorInfo || false
				message.success('操作成功')
				if (!response.data.hasErrorInfo) {
					getDate(response.data.id)
					footerBtnShow.value = true
				} else {
					grid.value.loadData(response.data.cachedDataList)
					visibles.tableList = response.data.cachedDataList
					visibles.dataList = response.data.cachedDataList
					visibles.total = response.data.cachedDataList.length
					footerBtnShow.value = false
				}
			}
		}
	})
	// 查询导入数据
	const getDate = id => {
		let parameters = {id: id, current: 1}
		recordList(parameters).then(response => {
			grid.value.loadData(response.data)
			visibles.tableList = response.data
			visibles.dataList = response.data
			visibles.total = response.data.length
			gridOptions.data = cutPage(visibles.current, visibles.size, visibles.dataList || [])
		})
	}
	//重置
	const resetClick = () => {
		requestInfo.value.length = 0
		grid.value.remove()
		footerBtnShow.value = false
		generateBillBtnShow.value = false
		modelRef.value.configId = ''
		visibles.tableList = []
		visibles.dataList = []
	}
	// 表头
	const gridOptions = reactive<VxeGridProps>({
		height: '500',
		showOverflow: true,
		rowConfig: {
			height: 60,
			isHover: true
		},
		columns: [
			{
				title: '员工姓名',
				minWidth: 120,
				align: 'left',
				field: 'employeeName',
				slots: {
					header: 'headerName'
				}
			},
			{
				title: '员工电话',
				minWidth: 150,
				align: 'left',
				field: 'phone',
				slots: {
					header: 'headerPhone'
				}
			},
			{
				minWidth: 180,
				title: '员工身份证号',
				align: 'left',
				field: 'idCard',
				slots: {
					header: 'headerIdCare'
				}
			},
			{
				minWidth: 100,
				title: '员工性别',
				align: 'left',
				field: 'price',
				slots: {
					header: 'headerSex',
					default: 'gender'
				}
			},
			{
				minWidth: 150,
				title: '劳动合同开始日期',
				align: 'left',
				slots: {
					default: 'laborContractBeginTime'
				}
			},
			{
				minWidth: 150,
				title: '劳动合同结束日期',
				align: 'left',
				slots: {
					default: 'laborContractEndTime'
				}
			},
			{
				minWidth: 260,
				title: '所属企业',
				align: 'left',
				field: 'enterpriseName',
				slots: {
					header: 'headerEmployee'
				}
			},
			{
				minWidth: 260,
				title: '社会统一信用代码',
				align: 'left',
				field: 'societyCode',
				slots: {
					header: 'headerCode'
				}
			},
			{
				minWidth: 280,
				fixed: 'right',
				align: 'left',
				slots: {
					default: 'content',
					header: 'headerErrMsg'
				}
			}
		]
	})

	const openedRecords = () => {
		visibles.records = true
	}

	const options = ref<any>({
		test: []
	})

	const modelRef = ref<any>({
		configId: null
	})

	const download = () => {
		employeeTemplate({}).then((res: any) => {
			const blob = new Blob([res], {
				type: 'application/vnd.ms-excel;charset=utf-8'
			})
			const link = document.createElement('a')
			link.href = window.URL.createObjectURL(blob)
			link.download = '员工批量导入模板.xls'
			link.click()
		})
	}

	const formRef = ref<any>()
	const add = () => {
		const employees = visibles.tableList.filter((e: any) => e?.employeeId && e.employeeId)
		let list: any = employees.map((o: any) => {
			return {employeeId: o.employeeId, recordId: o.id}
		})
		loading.value = true
		saveEmployee({
			refId: visibles.refId,
			employees: list
		}).then(() => {
			message.success('操作成功')
			loading.value = false
			modelRef.value.configId = null
			resetClick()
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		})
		// })
	}

	watch(
		() => props.visible,
		newVal => {
			if (!newVal) {
				footerBtnShow.value = false
				// resetClick()
				modelRef.value.configId = ''
				loading.value = false
			} else {
				modelRef.value.configId = null
				visibles.dataList = []
				visibles.tableList = []
			}
		}
	)

	onMounted(() => {
		getStorehouse({}).then((res: any) => {
			options.value.test = res.data
		})
	})

	// 切页
	const cutPage = (current: number, size: number, tableData: any) => {
		const start = (current - 1) * size
		const end = current * size

		return tableData.slice(start, end)
	}
	// 分页
	const handlePageChange: VxePagerEvents.PageChange = ({currentPage, pageSize}) => {
		visibles.current = currentPage
		visibles.size = pageSize
		visibles.tableList = cutPage(currentPage, pageSize, visibles.dataList)
		grid.value.refreshColumn()
	}
</script>

<style lang="less">
	.import-employee {
		.energy .vxe-pager--left-wrapper {
			position: absolute;
			left: 10px;
		}

		.color-faad14 {
			color: #faad14;
		}

		.ant-select-single.ant-select-show-arrow .ant-select-selection-item,
		.ant-select-single.ant-select-show-arrow .ant-select-selection-placeholder {
			text-align: left;
		}
		.bottom-btn {
			margin-top: 10px;
		}
		.pager-box {
			display: flex;
			justify-content: space-between;
			padding: 0 0 10px;
			vertical-align: middle;
		}
	}
</style>
